from scipy.sparse.linalg import eigsh
import scipy.sparse as sp
import scipy
import utils
import numpy as np

def norm(L, d):
    for i in range(d):
        col = L.getcol(i);
        nor =  np.linalg.norm(col.todense(), 'fro');
        print 'before', np.linalg.norm(L.getcol(i).todense());
        for j in range(L.indptr[i], indptr[i+1]):
            L.data[j] = L.data[j]/float(nor);
        print 'after', np.linalg.norm(L.getcol(i).todense());
        
def pls(W, N, dx, dy, batch_no):
    
    T = sp.eye(dx+dy, dx, format='csr');
    S = sp.eye(dx+dy, dy, -dx, format='csr');

    WW = S.dot(W).dot(T.transpose());
    NN = WW.transpose();

    U = WW + NN;
    print U.max(0).todense();
    print U.shape
    d = 100;
    evals_large, evecs_large = eigsh(U, 100, which='LM');
    
    print evecs_large.shape;
    E= sp.csc_matrix(evecs_large);
    
    print np.linalg.norm(E.getcol(0).todense());    
    Lx = T.transpose().dot(E);
    Ly = S.transpose().dot(E);

    #norm(Lx, d);
    #norm(Lx, d);
    print type(Lx);
    utils.save_sparse_csr('Lx_pls_%d.txt.npz'% (batch_no), sp.csr_matrix(Lx));
    utils.save_sparse_csr('Ly_pls_%d.txt.npz'% (batch_no), sp.csr_matrix(Ly));

if __name__ == '__main__':
    config = utils.get_config();
    dx = config.getint('rmls', 'dx');
    dy = config.getint('rmls', 'dy');
    # W = Cyx(dy*dx) N=Cxy(dx*dy);
    N = utils.load_sparse_csc('Nps.txt.npz');
    W = utils.load_sparse_csc('W_final.npz');
    batch_no = -1;
    pls(W, N, dx, dy, batch_no);

    
